package com.jfirer.mvc.core.route.impl;

import com.jfirer.mvc.core.route.RouteNode;
import com.jfirer.mvc.core.route.RouteTree;
import com.jfirer.mvc.core.route.Router;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

public class RouteTreeImpl implements RouteTree
{
    private RouteNode root = new RouteNodeImpl("root");

    @Override
    public Router route(String url, HttpServletRequest request)
    {
        String[] paths = transfer(url);
        return root.route(paths, 0, request);
    }

    @Override
    public Router resolve(String name, String url, String httpMethod, String... headerRules)
    {
        String[] paths = transfer(url);
        return root.resolve(name, paths, 0, httpMethod.toUpperCase(), headerRules);
    }

    private String[] transfer(String url)
    {
        List<String> list  = new ArrayList<String>();
        int          start = 0, end = 0;
        do
        {
            start = url.indexOf('/', end);
            if (start != -1)
            {
                end = url.indexOf('/', start + 1);
                end = end == -1 ? url.length() : end;
                String slice = url.substring(start + 1, end);
                list.add(slice);
            }
            else
            {
                break;
            }
        } while (true);
        return list.toArray(new String[list.size()]);
    }

    @Override
    public void finishResolve()
    {
        root.finishResolve();
    }
}
